package com.jinrustar.weimaqi.util

import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.BasicCookieStore
import org.apache.http.impl.client.HttpClientBuilder
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.nio.charset.Charset

/**
 * Created by liduanwei on 2017/10/26 0026. liduanwei1988@gmail.com
 */
object HttpUtil {
    private val cookieStore = BasicCookieStore()

    @Throws(IOException::class)
    fun httpPost(url: String, data: String): ByteArray {

        val httpPost = HttpPost(url)
        httpPost.addHeader("Content-type", "application/json; charset=utf-8")
        httpPost.entity = StringEntity(data, Charset.forName("UTF-8"))


        val httpResponse = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build().execute(httpPost)

        val buffer = ByteArray(1024 shl 1)
        var len = 0
        val byteArrayOutputStream = ByteArrayOutputStream()
        val inputStream = httpResponse.entity.content
        while (true) {
            len = inputStream.read(buffer)
            if (-1 == len) {
                break
            }
            byteArrayOutputStream.write(buffer, 0, len)
        }
        byteArrayOutputStream.close()
        inputStream.close()
        return byteArrayOutputStream.toByteArray()
    }
}